﻿using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Discovery;
using System.ServiceModel.Channels;
using System.Collections.ObjectModel;
using Nardax.ServiceModel.Discovery.Bindings;

namespace Nardax.ServiceModel.Discovery
{
    public class BindingDiscoveryServiceBehavior : IServiceBehavior
    {
        public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
        {
        }

        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            var endpoints = serviceDescription.Endpoints;


            foreach (var endpoint in endpoints)
            {
                var endpointDiscoveryBehavior = endpoint.Behaviors.Find<EndpointDiscoveryBehavior>();

                if (endpointDiscoveryBehavior == null)
                {
                    endpointDiscoveryBehavior = new EndpointDiscoveryBehavior();
                    endpoint.Behaviors.Add(endpointDiscoveryBehavior);
                }

                endpointDiscoveryBehavior.Extensions.Add(BindingSerializer.Serialize(endpoint.Binding));
            }
        }

        public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
        }
    }
}
